package org.springframework.samples.mvc.ajax.account;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.bazaarvoice.prr.util.BazaarvoiceUtils;

@Controller
@RequestMapping(value = "/jsapi")
public class JSAPIController {

	@RequestMapping(method = RequestMethod.GET)
	public String getCreateForm(Model model) {
		String smartSEO = getBazaarvoiceInjectionContainer("8016-sv_se", "9013704", "seo");
		model.addAttribute("seo", smartSEO);
		return "jsapi/jsapi";
	}

	@RequestMapping(value = "/submissionPage.html", method = RequestMethod.GET)
	public String getAccounts(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "bvauthenticateuser") String bvauthenticateuser,
			Model model) {
		List<Cookie> cookies = new ArrayList<Cookie>(Arrays.asList(request
				.getCookies()));
		Boolean loggedIn = false;
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("loggedIn")) {
				loggedIn = Boolean.valueOf(cookie.getValue());
				break;
			}
		}
		if (Boolean.valueOf(bvauthenticateuser) == true && !loggedIn) {
			return "redirect:/login?" + request.getQueryString();
		} else {
			String user = "";
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("userId")) {
					user += cookie.getValue();
					break;
				}
			}
			user += "&emailaddress=sample@gmail.com";
			String userId = BazaarvoiceUtils
					.encodeUserID(user,
							"6efCdrsDTZySakHD1Q5qnHjmJZgaToD8OEIwqdqeJNzCjP2Kg9i9jjzwpG2Mmv");
			model.addAttribute("userId", userId);
			return "jsapi/submission";
		}

	}
    private String getBazaarvoiceInjectionContainer(String displayCode, String productId, String smartSEOPathPrefix) {
        StringBuffer cntnrBuf = new StringBuffer();

        cntnrBuf.append("<div id=\"BVRRContainer\">\n");

        try {

            //Make sure the smartSEOPathPrefix ends with a trailing slash
            if (!smartSEOPathPrefix.endsWith("/")) {
                smartSEOPathPrefix += "/";
            }

            //Get the name of the file from disk that we should use to include in the page.
            File rrSmartSEOFile = new File(smartSEOPathPrefix + displayCode + "/reviews/product/1/" + URLEncoder.encode(productId, "UTF-8").replace("+", "%20") + ".htm");
            if (rrSmartSEOFile.exists() && rrSmartSEOFile.isFile()) {
                //Read in the file contents
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(rrSmartSEOFile), "UTF-8"));
                String line = null;
                String sep = System.getProperty("line.separator");
                while ((line = reader.readLine()) != null) {
                    cntnrBuf.append(line + sep);
                }
            }


        } catch(Exception e) {
            //log exception
            e.printStackTrace();
        } finally {
            cntnrBuf.append("</div>\n");
        }

        return cntnrBuf.toString();
    }
}
